﻿using Combination.Core;
using Combination.Model;
using Combination.UI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

namespace Combination.Client
{
    public class AccountEditPageVm : PageVm
    {
        #region Binding Propertys
        private readonly List<WebsiteItemVm> _stationCollection = new();

        /// <summary>
        /// 站点列表(搜索结果)
        /// </summary>
        public ObservableCollection<WebsiteItemVm> StationCollection { get; } = new ObservableCollection<WebsiteItemVm>();


        private WebsiteItemVm _selectedStation;
        /// <summary>
        /// 当前选择的站点
        /// </summary>
        public WebsiteItemVm SelectedStation
        {
            get { return _selectedStation; }
            set { _selectedStation = value; OnPropertyChanged(); OpenWebViewDialog(value); }
        }

        private string _searchText;
        /// <summary>
        /// 搜索的内容
        /// </summary>
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                OnPropertyChanged();
                SetStationCollection(_searchText);
            }
        }
        #endregion

        #region ctor
        public AccountEditPageVm()
        {
            if (!IsInDesignMode)
            {
                App.LocalData.CollectionChanged += LocalData_CollectionChanged;
            }
            //CreateTestStation();
            LoadAllStation();
        }
        #endregion

        #region private Methods

        private void LoadAllStation()
        {
            try
            {
                _stationCollection.Clear();
                var chatbots = App.LocalData.GetCollection<WebsiteData>();
                foreach (var chatbot in chatbots)
                {
                    var item = new WebsiteItemVm()
                    {
                        WebsiteData = App.Helper.CopyFrom<WebsiteDataVm>(chatbot)
                    };
                    _stationCollection.Add(item);
                }
                SetStationCollection(SearchText);                
            }
            catch
            {
                //nothing
            }
        }

        private void SetStationCollection(string searchText)
        {
            try
            {
                var orgSelectedChatbot = SelectedStation;
                var chatbotCollection = _stationCollection;
                if (string.IsNullOrWhiteSpace(searchText))
                {
                    if (StationCollection.Count != chatbotCollection.Count)
                    {
                        StationCollection.Clear();
                        foreach (var item in chatbotCollection)
                        {
                            StationCollection.Add(item);
                        }
                    }
                }
                else
                {
                    var resultChatbots = chatbotCollection.Where(p =>
                    {
                        return p.WebsiteData.Name?.Contains(searchText, StringComparison.OrdinalIgnoreCase) == true ||
                            p.WebsiteData.Name?.Contains(searchText, StringComparison.OrdinalIgnoreCase) == true;
                    }).ToArray();
                    if (!resultChatbots.SequenceEqual(StationCollection))
                    {
                        StationCollection.Clear();
                        foreach (var item in resultChatbots)
                        {
                            StationCollection.Add(item);
                        }
                    }
                }
                if (orgSelectedChatbot != null && StationCollection.Contains(orgSelectedChatbot))
                {
                    SelectedStation = orgSelectedChatbot;
                }
            }
            catch
            {
                //nothing...
            }
        }

        private void LocalData_CollectionChanged(object sender, DataContextCollectionChangedEventArgs e)
        {
            try
            {
                if (e.DataType == typeof(WebsiteData))
                {
                    if (e.Action == DataContextCollectionChangedAction.Add)
                    {
                        foreach (var item in e.Items)
                        {
                            _stationCollection.Add(new WebsiteItemVm()
                            {
                                WebsiteData = App.Helper.CopyFrom<WebsiteDataVm>(item)
                            });
                        }
                    }
                    else if (e.Action == DataContextCollectionChangedAction.Update)
                    {
                        foreach (WebsiteData item in e.Items)
                        {
                            var dataVm = _stationCollection.FirstOrDefault(p => p.WebsiteData.ID == item.ID);
                            if (dataVm == null)
                            {
                                _stationCollection.Add(new WebsiteItemVm()
                                {
                                    WebsiteData = App.Helper.CopyFrom<WebsiteDataVm>(item)
                                });
                            }
                            else
                            {
                                dataVm.WebsiteData = App.Helper.CopyFrom<WebsiteDataVm>(item);
                            }
                        }
                    }
                    else if (e.Action == DataContextCollectionChangedAction.Delete)
                    {
                        foreach (WebsiteData item in e.Items)
                        {
                            var dataVm = _stationCollection.FirstOrDefault(p => p.WebsiteData.ID == item.ID);
                            if (dataVm != null)
                            {
                                _stationCollection.Remove(dataVm);
                            }
                        }

                    }
                    SetStationCollection(SearchText);
                }
            }
            catch
            {
                //nothing
            }
        }

        private void CreateTestStation()
        {
            var filePaths = Directory.GetFiles(@"E:\Work\Combination.Client\Image", "*.png", SearchOption.TopDirectoryOnly).OrderBy(d => new FileInfo(d).CreationTime);
            foreach (var filePath in filePaths)
            {
                var imageText = App.Helper.GetBase64Image(filePath, 128, 128);
                var newData = new WebsiteData
                {
                    ID = Guid.NewGuid().ToString(),
                    Name = Path.GetFileNameWithoutExtension(filePath),
                    IsPop = true,
                    Image = imageText
                };
                App.LocalData.SetItem(newData);
            }
        }

        private static void OpenWebViewDialog(WebsiteItemVm website)
        {
            FormPage page = new WebViewPage
            {
                DataContext = new WebViewPageVm(website),
                AfterFormValidateHandle = dataContext =>
                {
                    return ResponseValidationResult.Ok();
                }
            };
            PageDialog.Show("登录帐号", page, MessageButtons.Close);
        }
        #endregion
    }
}
